package org.jimm.service;

import org.jimm.app.ChatActivity;
import org.jimm.app.ContactListActivity;
import org.jimm.app.JimmActivity;
import org.jimm.app.JimmApplication;
import org.jimm.app.NotificationMan;
import org.jimm.db.JimmDatabase.History;
import org.jimm.message.PlainMessage;
import org.jimm.protocol.AccountsManager;
import org.jimm.protocol.Contact;
import org.jimm.protocol.Group;
import org.jimm.protocol.Protocol;
import org.jimm.protocol.ProtocolListener;

import android.app.Activity;
import android.app.Service;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;

import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public final class JimmService extends Service implements ProtocolListener {
    private static final String LOG_TAG = "Jimm:JimmService";

    private final LocalBinder localBinder = new LocalBinder();
    public MyHandler handler;

    //	private ContentResolver contentResolver;
    private PowerManager.WakeLock wakeLock;

    public ChatActivity chatActivity;
    public ContactListActivity contactlistActivity;

    private AccountsManager accountsManager;

    public static final int M_SHOW_TOAST = 0;
    public static final int M_INVALIDATE_VIEW = 1;

    public class LocalBinder extends Binder {
        public JimmService getService() {
            return JimmService.this;
        }
    }

    public class MyHandler extends Handler {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case M_SHOW_TOAST:
                    String text = (String) msg.obj;
                    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                    break;

                case M_INVALIDATE_VIEW:
                    View v = (View) msg.obj;
                    if (v != null) v.invalidate();
                    break;

                default:
                    Log.d(LOG_TAG, "Unknown message " + msg.what);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(LOG_TAG, "onCreate()");
        //setForeground(true); // todo what is it?
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Jimm");
        wakeLock.acquire();

        handler = new MyHandler();

        accountsManager = new AccountsManager(getContentResolver(), JimmApplication.getInstance().getPreferences());
        accountsManager.setProtocolListener(this);
    }

    @Override
    public void onDestroy() {
        Log.i(LOG_TAG, "onDestroy()");

        // clear the notification
        stopForeground(true);
        getAccountsManager().disconnectAll();
        NotificationMan.clearNotifications();

        super.onDestroy();
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return localBinder;
    }

    public JimmActivity getCurrentActivity() {

        if (chatActivity != null) {
            if (chatActivity.hasWindowFocus())
                return chatActivity;
        }

        return contactlistActivity;
    }

    public AccountsManager getAccountsManager() {
        return accountsManager;
    }


    // This is the old onStart method that will be called on the pre-2.0
    // platform.  On 2.0 or later we override onStartCommand() so this
    // method will not be called.
    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(LOG_TAG, "onStart");
        handleCommand(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    void handleCommand(Intent intent) {
    }

    @Override
    public void onConnected(Protocol p) {

        getCurrentActivity().invalidate();
        ((Activity) getCurrentActivity()).runOnUiThread(new Runnable() {

            public void run() {
                NotificationMan.updateNotifications(JimmService.this);
            }
        });
    }

    @Override
    public void onDisconnected(Protocol p) {

        getCurrentActivity().invalidate();
        ((Activity) getCurrentActivity()).runOnUiThread(new Runnable() {

            public void run() {
                NotificationMan.updateNotifications(JimmService.this);
            }
        });
    }

    @Override
    public void onUpdateConnectingProgress(Protocol p, final int percent) {
        Log.i(LOG_TAG, "Connecting: " + percent + "%");

        ((Activity) getCurrentActivity()).runOnUiThread(new Runnable() {

            public void run() {
                Toast.makeText(((Activity) getCurrentActivity()), "Connecting: " + percent + "%", Toast.LENGTH_SHORT).show();
            }
        });
        getCurrentActivity().invalidate();
    }

    @Override
    public void onUpdateContacList(Protocol p, final Contact c) {

        ((Activity) getCurrentActivity()).runOnUiThread(new Runnable() {
            public void run() {
                //View v = c.getConvertView();
                //if (v != null) v.invalidate();
            }
        });
        getCurrentActivity().invalidate();
    }

    @Override
    public void onUpdateContacList(Protocol p, final Group g) {
        ((Activity) getCurrentActivity()).runOnUiThread(new Runnable() {
            public void run() {
                //View v = g.getConvertView();
                //if (v != null) v.invalidate();
            }
        });
        getCurrentActivity().invalidate();
    }

    @Override
    public void onMessage(Protocol p, Contact c, PlainMessage m) {

        //notifications.onInputMessage();

        m.getRcvr().messages.add(m);
        getCurrentActivity().invalidate();

        // �������� ��������� � ����
        ContentValues values = new ContentValues();

        String accountUid = p.getUserId();
        String contactUid = c.getUserId();
        long date = System.currentTimeMillis();

        values.put(History.ACCOUNT, accountUid);
        values.put(History.CONTACT, contactUid);
        values.put(History.DATE, date);
        values.put(History.FLAGS, History.FLAG_RECEIVED_MESSAGE);
        values.put(History.MESSAGE, m.getText());

        getContentResolver().insert(History.CONTENT_URI, values);

        Log.i(LOG_TAG, "msg: from = " + m.getSndrUin() + ", text = " + m.getText());

        ((Activity) getCurrentActivity()).runOnUiThread(new Runnable() {

            public void run() {
                NotificationMan.updateNotifications(JimmService.this);
            }
        });
        getCurrentActivity().invalidate();
    }
}
